package com.yq.cp.service.basics.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yq.cp.config.MyException;
import com.yq.cp.entity.basics.*;
import com.yq.cp.entity.basics.model.SiteHeaderToUser;
import com.yq.cp.entity.basics.model.UserToStructureModel;
import com.yq.cp.entity.common.ErrorCode;
import com.yq.cp.entity.common.PageVo;
import com.yq.cp.entity.permission.Role;
import com.yq.cp.entity.permission.User;
import com.yq.cp.entity.permission.UserRole;
import com.yq.cp.entity.permission.vo.UserVo;
import com.yq.cp.mapper.basics.*;
import com.yq.cp.mapper.permission.RoleMapper;
import com.yq.cp.mapper.permission.UserMapper;
import com.yq.cp.mapper.permission.UserRoleMapper;
import com.yq.cp.service.basics.OrganizationalStructureService;
import com.yq.cp.utils.DateTimeUtil;
import com.yq.cp.utils.MD5Util;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 组织架构 服务实现类
 * </p>
 *
 * @author shenyuqing
 * @since 2024-08-27
 */
@Service
public class OrganizationalStructureServiceImpl extends ServiceImpl<OrganizationalStructureMapper, OrganizationalStructure> implements OrganizationalStructureService {
    @Resource
    OrganizationalStructureMapper organizationalStructureMapper;
    @Resource
    UserMapper userMapper;
    @Resource
    UserRoleMapper userRoleMapper;
    @Resource
    RoleMapper roleMapper;
    @Resource
    AreaMapper areaMapper;
    @Resource
    ProvincesMapper provincesMapper;
    @Resource
    CitiesMapper citiesMapper;
    @Resource
    AreasMapper areasMapper;
    @Override
    public void add(OrganizationalStructure vo ) {
        if (!vo.getUser().getPassword().equals(vo.getUser().getNewPassword()))
            throw new MyException("两次密码不相同，请确认密码后再提交!!!");
        vo.setExamine(0);
        vo.getUser().setRoleId(3L);
        if (!Objects.isNull(vo.getNowId()))
            vo.setId(vo.getNowId());
        organizationalStructureMapper.insert(vo);

        if (vo.getUser().getUsername()==null || vo.getUser().getUsername()==""){
            vo.getUser().setUsername(vo.getUser().getPhone());
        }
        if (vo.getUser().getRoleId()==null){
            throw new MyException(ErrorCode.ERROR_500);
        }
        if(!this.arguments(vo.getUser())){//参数是否合法
            throw new MyException(ErrorCode.ERROR_500);
        }
        if(this.isExist(vo.getUser().getUsername(),null)){//用户名是否重复
            throw new MyException(ErrorCode.USER_1110);
        }
        Role role = roleMapper.selectById(vo.getUser().getRoleId());
        User user=new User();
        user.setUsername(vo.getUser().getUsername());
        user.setPassword(MD5Util.encode(vo.getUser().getPassword()));
        user.setPhone(vo.getUser().getPhone());
        user.setNickname(vo.getUser().getNickname());
        user.setHeadPortrait(vo.getUser().getHeadPortrait());
        user.setMailbox(vo.getUser().getMailbox());
        user.setType(role.getType());
        user.setCreateUserId(vo.getCreateUserId());
        user.setState(0);
        user.setExamine(0);
        user.setElectronicSignature(vo.getUser().getElectronicSignature());
        user.setStructureId(vo.getId());
        if (role.getType()==10 || role.getType()==11){
            user.setCompanyId(-1L);
        }
        userMapper.insert(user);

        //添加关系
        UserRole userRole=new UserRole();
        userRole.setUserId(user.getId());
        userRole.setRoleId(role.getId());
        userRole.setCreateUserId(vo.getCreateUserId());
        userRoleMapper.insert(userRole);


    }

    @Override
    public IPage<UserToStructureModel> channelExamineList(PageVo vo) {
        IPage<UserToStructureModel> page = new Page<>(vo.getPage(),vo.getSize());
        page =organizationalStructureMapper.channelExamineList(page,vo);
        if (!page.getRecords().isEmpty()){
            for (UserToStructureModel record : page.getRecords()) {
                List<OrganizationalStructure> structures = organizationalStructureMapper.selectList(new QueryWrapper<OrganizationalStructure>()
                        .eq("parent_id", record.getId()));
                if (structures.isEmpty())
                    continue;
                List<Area> areas = areaMapper.selectBatchIds(structures.stream().map(OrganizationalStructure::getAssociationId).collect(Collectors.toList()));
                record.setAreas(areas);
            }

        }
        return page;
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void channelEdit(OrganizationalStructure vo) {
        if (!Objects.isNull(vo.getAreas())&&!vo.getAreas().isEmpty()){
            try{
                List<Long> longList =  new ArrayList<>();
                List<OrganizationalStructure> structures = organizationalStructureMapper.selectList(new QueryWrapper<OrganizationalStructure>()
                        .eq("parent_id", vo.getId()));
                for (Area area : vo.getAreas()) {
                    for (int i = 0;i< structures.size();i++) {
                        if (structures.get(i).getAssociationId().equals(area.getId())) {
                            structures.remove(i);
                            i--;
                        }
                    }
                }
                if (structures.size()>0){
                    for (OrganizationalStructure structure : structures) {
                        List<OrganizationalStructure> regionId = organizationalStructureMapper.selectList(new QueryWrapper<OrganizationalStructure>()
                                .eq("region_id", structure.getId()).lt("type",6));
                        List<Long> collect = regionId.stream().map(OrganizationalStructure::getId).collect(Collectors.toList());
                        List<User> structureId = userMapper.selectList(new QueryWrapper<User>()
                                        .eq("examine",1)
                                .in("structure_id", collect));
                        if (!structureId.isEmpty())
                            throw new MyException(structure.getName()+"下还有数据绑定，请解除绑定后再试！！！");
                        List<OrganizationalStructure> regionId1 = organizationalStructureMapper.selectList(new QueryWrapper<OrganizationalStructure>()
                                .eq("region_id", structure.getId()).eq("type",6));
                        if (!regionId1.isEmpty()){
                            List<Long> collect1 = regionId1.stream().map(OrganizationalStructure::getId).collect(Collectors.toList());
                            List<User> structureIds = userMapper.selectList(new QueryWrapper<User>()
                                    .eq("examine",1)
                                    .in("site_id", collect1));
                            if (!structureIds.isEmpty())
                                throw new MyException(structure.getName()+"下还有数据绑定，请解除绑定后再试！！！");
                        }
                        organizationalStructureMapper.delete(new QueryWrapper<OrganizationalStructure>()
                                .eq("region_id", structure.getId()));
                        organizationalStructureMapper.deleteById(structure);
                    }

                }
            }catch (Exception e){
                throw e;
            }

            for (Area area : vo.getAreas()) {
                OrganizationalStructure organizationalStructuress = organizationalStructureMapper.selectOne(new QueryWrapper<OrganizationalStructure>()
                        .eq("parent_id", vo.getId()).eq("association_id", area.getId()));
                if (Objects.isNull(organizationalStructuress)){
                    Area area1 = areaMapper.selectById(area);
                    OrganizationalStructure structure = new OrganizationalStructure();
                    structure.setParentId(vo.getId());
                    structure.setChannelId(vo.getId());
                    structure.setChannelName(vo.getName());
                    structure.setName(area1.getName());
                    structure.setType(2);
                    structure.setExamine(1);
                    structure.setAssociationId(area.getId());
                    organizationalStructureMapper.insert(structure);
                    List<Area> areas = areaMapper.selectList(new QueryWrapper<Area>().eq("parent_id", area1.getId()));
                    for (Area area2 : areas) {
                        OrganizationalStructure structuresheng =   new OrganizationalStructure();
                        structuresheng.setParentId(structure.getId());
                        Provinces byId1 =provincesMapper.selectOne(new QueryWrapper<Provinces>()
                                .eq("provinceid",area2.getShengId()));
                        structuresheng.setName(byId1.getProvince());
                        structuresheng.setChannelId(vo.getId());
                        structuresheng.setChannelName(vo.getName());
                        structuresheng.setRegionId(structure.getId());
                        structuresheng.setRegionName(structure.getName());
                        structuresheng.setType(3);
                        structuresheng.setExamine(1);
                        organizationalStructureMapper.insert(structuresheng);
                        List<Cities> cities = citiesMapper.selectList(new QueryWrapper<Cities>()
                                .eq("provinceid", byId1.getProvinceid()));
                        for (Cities city : cities) {
                            OrganizationalStructure organizationalStructure =   new OrganizationalStructure();
                            organizationalStructure.setParentId(structuresheng.getId());
                            organizationalStructure.setName(city.getCity());
                            organizationalStructure.setChannelId(vo.getId());
                            organizationalStructure.setChannelName(vo.getName());
                            organizationalStructure.setRegionId(structure.getId());
                            organizationalStructure.setRegionName(structure.getName());
                            organizationalStructure.setShengId(structuresheng.getId());
                            organizationalStructure.setShengName(structuresheng.getName());
                            organizationalStructure.setType(4);
                            organizationalStructure.setExamine(1);
                            organizationalStructureMapper.insert(organizationalStructure);
                            List<Areas> areas1 = areasMapper.selectList(new QueryWrapper<Areas>()
                                    .eq("cityid", city.getCityid()));
                            for (Areas areas2 : areas1) {
                                OrganizationalStructure organizae =   new OrganizationalStructure();
                                organizae.setParentId(organizationalStructure.getId());
                                organizae.setName(areas2.getArea());
                                organizae.setChannelId(vo.getId());
                                organizae.setChannelName(vo.getName());
                                organizae.setRegionId(structure.getId());
                                organizae.setRegionName(structure.getName());
                                organizae.setShengId(structuresheng.getId());
                                organizae.setShengName(structuresheng.getName());
                                organizae.setShiId(organizationalStructure.getId());
                                organizae.setShiName(organizationalStructure.getName());
                                organizae.setType(5);
                                organizae.setExamine(1);
                                organizationalStructureMapper.insert(organizae);
                            }
                        }
                    }
                }
            }
        }
        vo.getUser().setRoleId(3L);
        organizationalStructureMapper.updateById(vo);
        if (vo.getUser().getUsername()==null || vo.getUser().getUsername()==""){
            vo.getUser().setUsername(vo.getUser().getPhone());
        }

        if (vo.getUser().getRoleId() == null) {
            throw new MyException(ErrorCode.ERROR_500);
        }
        if(!this.arguments(vo.getUser())){//参数是否合法
            throw new MyException(ErrorCode.ERROR_500);
        }
//        if(this.isExist(vo.getUser().getUsername(),vo.getId())){//用户名是否重复
//            throw new MyException(ErrorCode.USER_1110);
//        }
        Role role = roleMapper.selectById(vo.getUser().getRoleId());
        if (role==null){
            throw new MyException(ErrorCode.role_1201);
        }
        User user = userMapper.selectOne(new QueryWrapper<User>()
                .eq("structure_id", vo.getId()));
        //User user = userMapper.selectById(vo.getId());
        user.setUsername(vo.getUser().getUsername());
        if (vo.getUser().getPassword()!=null && !vo.getUser().getPassword().equals("")){
            user.setPassword(MD5Util.encode(vo.getUser().getPassword()));
        }

        user.setPhone(vo.getUser().getPhone());
        user.setNickname(vo.getUser().getNickname());
        user.setHeadPortrait(vo.getUser().getHeadPortrait());
        user.setMailbox(vo.getUser().getMailbox());
        user.setElectronicSignature(vo.getUser().getElectronicSignature());
        user.setType(role.getType());
        userMapper.updateById(user);

        //删除关系
        userRoleMapper.deleteByUserId(user.getId());
        //添加关系
        UserRole userRole=new UserRole();
        userRole.setUserId(user.getId());
        userRole.setRoleId(role.getId());
        userRole.setCreateUserId(vo.getCreateUserId());
        userRoleMapper.insert(userRole);

    }

    @Override
    public IPage<OrganizationalStructure> siteList(PageVo vo) {
        IPage<OrganizationalStructure> page = new Page<>(vo.getPage(), vo.getSize());
        page = organizationalStructureMapper.siteList(page,vo);
        return page;
    }

    @Override
    public IPage<SiteHeaderToUser> siteHeaderExamineList(PageVo vo) {
        IPage<SiteHeaderToUser> page = new Page<>(vo.getPage(),vo.getSize());
        page =organizationalStructureMapper.siteHeaderExamineList(page,vo);
        if (!page.getRecords().isEmpty()){
            for (SiteHeaderToUser record : page.getRecords()) {
                OrganizationalStructure structure = organizationalStructureMapper.selectById(record.getStructureId());
                record.setSiteName(structure.getName());
                record.setSiteId(record.getStructureId());
            }
        }
        return page;
    }

    @Override
    public void huanyuan(OrganizationalStructure byId) {
        organizationalStructureMapper.huanyuan(byId.getId());
    }

    @Override
    public IPage<UserToStructureModel> channelExamineListgai(PageVo vo) {
        IPage<UserToStructureModel> page = new Page<>(vo.getPage(),vo.getSize());
        page =organizationalStructureMapper.channelExamineList(page,vo);
        if (!page.getRecords().isEmpty()){
            for (UserToStructureModel record : page.getRecords()) {
                record.setPassword(MD5Util.decoder(record.getPassword()));
                if (vo.getType()==2){
                    OrganizationalStructure structure = organizationalStructureMapper.selectById(record.getParentId());
                    record.setChannelName(structure.getName());
                    record.setChannelId(structure.getId());
                    Area area = areaMapper.selectById(record.getNowId());
                    record.setName(area.getName());
                }
                if (vo.getType()==3){
                    OrganizationalStructure structuredaqu = organizationalStructureMapper.selectById(record.getParentId());
                    OrganizationalStructure structurequdao = organizationalStructureMapper.selectById(structuredaqu.getParentId());
                    record.setChannelName(structurequdao.getName());
                    record.setChannelId(structurequdao.getId());
                    Area area = areaMapper.selectById(structuredaqu.getNowId());
                    Area area1 = areaMapper.selectOne(new QueryWrapper<Area>()
                            .eq("parent_id",area.getId()).eq("sheng_id",record.getNowId()));
                    record.setRegionName(area.getName());
                    record.setRegionId(structuredaqu.getId());
                    Provinces byId1 =provincesMapper.selectOne(new QueryWrapper<Provinces>()
                            .eq("provinceid",record.getNowId()));
                    record.setName(byId1.getProvince());
                    record.setShengId(area1.getId());
                }
                if (vo.getType()==4){
                    OrganizationalStructure structuresheng = organizationalStructureMapper.selectById(record.getParentId());
                    OrganizationalStructure structuredaqu = organizationalStructureMapper.selectById(structuresheng.getParentId());
                    OrganizationalStructure structurequdao = organizationalStructureMapper.selectById(structuredaqu.getParentId());
                    record.setChannelName(structurequdao.getName());
                    record.setChannelId(structurequdao.getId());
                    Area area = areaMapper.selectById(structuredaqu.getNowId());
                    record.setRegionName(area.getName());
                    record.setRegionId(structuredaqu.getId());
                    Provinces byId1 =provincesMapper.selectOne(new QueryWrapper<Provinces>()
                            .eq("provinceid",structuresheng.getNowId()));
                    record.setShengName(byId1.getProvince());
                    record.setShengId(structuresheng.getId());
                    Cities byId =citiesMapper.selectOne(new QueryWrapper<Cities>()
                            .eq("cityid",record.getNowId()));
                    record.setName(byId.getCity());
                }
                if (vo.getType()==5){
                    OrganizationalStructure structureshi = organizationalStructureMapper.selectById(record.getParentId());
                    OrganizationalStructure structuresheng = organizationalStructureMapper.selectById(structureshi.getParentId());
                    OrganizationalStructure structuredaqu = organizationalStructureMapper.selectById(structuresheng.getParentId());
                    OrganizationalStructure structurequdao = organizationalStructureMapper.selectById(structuredaqu.getParentId());
                    record.setChannelName(structurequdao.getName());
                    record.setChannelId(structurequdao.getId());
                    Area area = areaMapper.selectById(structuredaqu.getNowId());
                    record.setRegionName(area.getName());
                    record.setRegionId(structuredaqu.getId());
                    Provinces byId1 =provincesMapper.selectOne(new QueryWrapper<Provinces>()
                            .eq("provinceid",structuresheng.getNowId()));
                    record.setShengName(byId1.getProvince());
                    record.setShengId(structuresheng.getId());
                    Cities byId =citiesMapper.selectOne(new QueryWrapper<Cities>()
                            .eq("cityid",structureshi.getNowId()));
                    record.setShiName(byId.getCity());
                    record.setShiId(structureshi.getId());
                    Areas areaid = areasMapper.selectOne(new QueryWrapper<Areas>()
                            .eq("areaid", record.getNowId()));
                    record.setName(areaid.getArea());
                }
            }

        }
        return page;
    }

    @Override
    public IPage<OrganizationalStructure> siteListGai(PageVo vo) {
        IPage<OrganizationalStructure> page = new Page<>(vo.getPage(), vo.getSize());
        page = organizationalStructureMapper.siteList(page,vo);
        if (!page.getRecords().isEmpty()){
            for (OrganizationalStructure record : page.getRecords()) {
                OrganizationalStructure structure = organizationalStructureMapper.selectById(record.getChannelId());
                record.setChannelName(structure.getName());
                OrganizationalStructure structure1 = organizationalStructureMapper.selectById(record.getRegionId());
                record.setRegionName(structure1.getName());
                OrganizationalStructure structure2 = organizationalStructureMapper.selectById(record.getShengId());
                record.setShengName(structure2.getName());
                OrganizationalStructure structure3= organizationalStructureMapper.selectById(record.getShiId());
                record.setShiName(structure3.getName());
                OrganizationalStructure structure4= organizationalStructureMapper.selectById(record.getQuId());
                record.setQuName(structure4.getName());
            }
        }
        return page;
    }

    @Override
    public void guanlian(OrganizationalStructure vo) {
        vo.getUser().setRoleId(3L);
        if (!vo.getUser().getPassword().equals(vo.getUser().getNewPassword()))
            throw new MyException("两次密码不相同，请确认密码后再提交!!!");
        if(this.isExist(vo.getUser().getUsername(),null)){//用户名是否重复
            throw new MyException(ErrorCode.USER_1110);
        }
        if (vo.getUser().getUsername()==null || vo.getUser().getUsername()==""){
            vo.getUser().setUsername(vo.getUser().getPhone());
        }
        if (vo.getUser().getRoleId()==null){
            throw new MyException(ErrorCode.ERROR_500);
        }
        if(!this.arguments(vo.getUser())){//参数是否合法
            throw new MyException(ErrorCode.ERROR_500);
        }

        vo.setExamine(0);
        if (!Objects.isNull(vo.getNowId()))
            vo.setId(vo.getNowId());
        organizationalStructureMapper.insert(vo);
        if (!Objects.isNull(vo.getAreas())&&!vo.getAreas().isEmpty()){

//            List<Area> sum = new ArrayList<>();
//            List<Cities> sum1 = new ArrayList<>();
//            List<Areas> sum2 = new ArrayList<>();
//            for (Area area : vo.getAreas()) {
//                Area area1 = areaMapper.selectById(area);
//                OrganizationalStructure structure = new OrganizationalStructure();
//                structure.setParentId(vo.getId());
//                structure.setChannelId(vo.getId());
//                structure.setChannelName(vo.getName());
//                structure.setName(area1.getName());
//                structure.setType(2);
//                structure.setExamine(0);
//                structure.setAssociationId(area.getId());
//                organizationalStructureMapper.insert(structure);
//                List<Area> areas = areaMapper.selectList(new QueryWrapper<Area>().eq("parent_id", area1.getId()));
//                for (Area area2 : areas) {
//                    sum.add(area2);
//                }
//            }
//            for (Area area : sum) {
//                OrganizationalStructure structure = organizationalStructureMapper.selectOne(new QueryWrapper<OrganizationalStructure>()
//                        .eq("channel_id",vo.getId()) .eq("association_id", area.getParentId()));
//                OrganizationalStructure structuresheng =   new OrganizationalStructure();
//                structuresheng.setParentId(structure.getId());
//                Provinces byId1 =provincesMapper.selectOne(new QueryWrapper<Provinces>()
//                        .eq("provinceid",area.getShengId()));
//                structuresheng.setName(byId1.getProvince());
//                structuresheng.setChannelId(vo.getId());
//                structuresheng.setChannelName(vo.getName());
//                structuresheng.setRegionId(structure.getId());
//                structuresheng.setRegionName(structure.getName());
//                structuresheng.setType(3);
//                structuresheng.setExamine(0);
//                structuresheng.setAssociationId(area.getShengId());
//                organizationalStructureMapper.insert(structuresheng);
//                List<Cities> cities = citiesMapper.selectList(new QueryWrapper<Cities>()
//                        .eq("provinceid", byId1.getProvinceid()));
//                for (Cities city : cities) {
//                    sum1.add(city);
//                }
//            }
//            for (Cities city : sum1) {
//                OrganizationalStructure structuresheng = organizationalStructureMapper.selectOne(new QueryWrapper<OrganizationalStructure>()
//                        .eq("channel_id",vo.getId()).eq("association_id", city.getProvinceid()));
//                OrganizationalStructure organizationalStructure =   new OrganizationalStructure();
//                organizationalStructure.setParentId(structuresheng.getId());
//                organizationalStructure.setName(city.getCity());
//                organizationalStructure.setChannelId(vo.getId());
//                organizationalStructure.setChannelName(vo.getName());
//                organizationalStructure.setRegionId(structuresheng.getRegionId());
//                organizationalStructure.setRegionName(structuresheng.getRegionName());
//                organizationalStructure.setShengId(structuresheng.getId());
//                organizationalStructure.setShengName(structuresheng.getName());
//                organizationalStructure.setType(4);
//                organizationalStructure.setAssociationId(Long.parseLong(city.getCityid()));
//                organizationalStructure.setExamine(0);
//                organizationalStructureMapper.insert(organizationalStructure);
//                List<Areas> areas1 = areasMapper.selectList(new QueryWrapper<Areas>()
//                        .eq("cityid", city.getCityid()));
//                for (Areas areas : areas1) {
//                    sum2.add(areas);
//                }
//            }
//            for (Areas areas : sum2) {
//                OrganizationalStructure organizationalStructure = organizationalStructureMapper.selectOne(new QueryWrapper<OrganizationalStructure>()
//                        .eq("channel_id",vo.getId()).eq("association_id", areas.getCityid()));
//                OrganizationalStructure organizae =   new OrganizationalStructure();
//                organizae.setParentId(organizationalStructure.getId());
//                organizae.setName(areas.getArea());
//                organizae.setChannelId(vo.getId());
//                organizae.setChannelName(vo.getName());
//                organizae.setRegionId(organizationalStructure.getRegionId());
//                organizae.setRegionName(organizationalStructure.getRegionName());
//                organizae.setShengId(organizationalStructure.getShengId());
//                organizae.setShengName(organizationalStructure.getShengName());
//                organizae.setShiId(organizationalStructure.getId());
//                organizae.setShiName(organizationalStructure.getName());
//                organizae.setType(5);
//                organizae.setExamine(0);
//                organizationalStructureMapper.insert(organizae);
//
//            }

            for (Area area : vo.getAreas()) {
                Area area1 = areaMapper.selectById(area);
                OrganizationalStructure structure = new OrganizationalStructure();
                structure.setParentId(vo.getId());
                structure.setChannelId(vo.getId());
                structure.setChannelName(vo.getName());
                structure.setName(area1.getName());
                structure.setType(2);
                structure.setExamine(0);
                structure.setAssociationId(area.getId());
                organizationalStructureMapper.insert(structure);
                List<Area> areas = areaMapper.selectList(new QueryWrapper<Area>().eq("parent_id", area1.getId()));
                for (Area area2 : areas) {
                    OrganizationalStructure structuresheng =   new OrganizationalStructure();
                    structuresheng.setParentId(structure.getId());
                    Provinces byId1 =provincesMapper.selectOne(new QueryWrapper<Provinces>()
                            .eq("provinceid",area2.getShengId()));
                    structuresheng.setName(byId1.getProvince());
                    structuresheng.setChannelId(vo.getId());
                    structuresheng.setChannelName(vo.getName());
                    structuresheng.setRegionId(structure.getId());
                    structuresheng.setRegionName(structure.getName());
                    structuresheng.setType(3);
                    structuresheng.setExamine(0);
                    organizationalStructureMapper.insert(structuresheng);
                    List<Cities> cities = citiesMapper.selectList(new QueryWrapper<Cities>()
                            .eq("provinceid", byId1.getProvinceid()));
                    for (Cities city : cities) {
                        OrganizationalStructure organizationalStructure =   new OrganizationalStructure();
                        organizationalStructure.setParentId(structuresheng.getId());
                        organizationalStructure.setName(city.getCity());
                        organizationalStructure.setChannelId(vo.getId());
                        organizationalStructure.setChannelName(vo.getName());
                        organizationalStructure.setRegionId(structure.getId());
                        organizationalStructure.setRegionName(structure.getName());
                        organizationalStructure.setShengId(structuresheng.getId());
                        organizationalStructure.setShengName(structuresheng.getName());
                        organizationalStructure.setType(4);
                        organizationalStructure.setExamine(0);
                        organizationalStructureMapper.insert(organizationalStructure);
                        List<Areas> areas1 = areasMapper.selectList(new QueryWrapper<Areas>()
                                .eq("cityid", city.getCityid()));
                        for (Areas areas2 : areas1) {
                            OrganizationalStructure organizae =   new OrganizationalStructure();
                            organizae.setParentId(organizationalStructure.getId());
                            organizae.setName(areas2.getArea());
                            organizae.setChannelId(vo.getId());
                            organizae.setChannelName(vo.getName());
                            organizae.setRegionId(structure.getId());
                            organizae.setRegionName(structure.getName());
                            organizae.setShengId(structuresheng.getId());
                            organizae.setShengName(structuresheng.getName());
                            organizae.setShiId(organizationalStructure.getId());
                            organizae.setShiName(organizationalStructure.getName());
                            organizae.setType(5);
                            organizae.setExamine(0);
                            organizationalStructureMapper.insert(organizae);
                        }
                    }
                }
            }

        }

        Role role = roleMapper.selectById(vo.getUser().getRoleId());
        User user=new User();
        user.setUsername(vo.getUser().getUsername());
        user.setPassword(MD5Util.encode(vo.getUser().getPassword()));
        user.setPhone(vo.getUser().getPhone());
        user.setNickname(vo.getUser().getNickname());
        user.setHeadPortrait(vo.getUser().getHeadPortrait());
        user.setMailbox(vo.getUser().getMailbox());
        user.setType(role.getType());
        user.setCreateUserId(vo.getCreateUserId());
        user.setState(0);
        user.setElectronicSignature(vo.getUser().getElectronicSignature());
        user.setExamine(0);
        user.setStructureId(vo.getId());
        if (role.getType()==10 || role.getType()==11){
            user.setCompanyId(-1L);
        }
        userMapper.insert(user);
        //添加关系
        UserRole userRole=new UserRole();
        userRole.setUserId(user.getId());
        userRole.setRoleId(role.getId());
        userRole.setCreateUserId(vo.getCreateUserId());
        userRoleMapper.insert(userRole);


    }

    @Override
    public IPage<SiteHeaderToUser> channelExamineListevery(PageVo vo) {
        IPage<SiteHeaderToUser> page = new Page<>(vo.getPage(),vo.getSize());
        page =organizationalStructureMapper.channelExamineListevery(page,vo);
        if (!page.getRecords().isEmpty()){
            for (SiteHeaderToUser record : page.getRecords()) {
                if (vo.getType()==2) {
                    OrganizationalStructure structure = organizationalStructureMapper.selectById(record.getStructureId());
                    record.setName(structure.getName());
                    record.setRegionName(structure.getName());
                    record.setRegionId(record.getDangqianid());
                    //record.setSiteId(record.getStructureId());
                }
                if (vo.getType()==3) {
                    OrganizationalStructure structure = organizationalStructureMapper.selectById(record.getStructureId());
                    record.setName(structure.getName());
                    record.setShengName(structure.getName());
                    record.setShengId(record.getDangqianid());
                    //record.setSiteId(record.getStructureId());
                }
                if (vo.getType()==4) {
                    OrganizationalStructure structure = organizationalStructureMapper.selectById(record.getStructureId());
                    record.setName(structure.getName());
                    record.setShiName(structure.getName());
                    record.setShiId(record.getDangqianid());
                    //record.setSiteId(record.getStructureId());
                }
                if (vo.getType()==5) {
                    OrganizationalStructure structure = organizationalStructureMapper.selectById(record.getStructureId());
                    record.setName(structure.getName());
                    record.setQuName(structure.getName());
                    record.setQuId(record.getDangqianid());
                    //record.setSiteId(record.getStructureId());
                }
            }
        }
        return page;
    }

    @Override
    public void channelAddCeshi(OrganizationalStructure vo) {
        organizationalStructureMapper.insert(vo);
        if (!Objects.isNull(vo.getAreas())&&!vo.getAreas().isEmpty()){
            List<Area> sum = new ArrayList<>();
            List<Cities> sum1 = new ArrayList<>();
            List<Areas> sum2 = new ArrayList<>();
            for (Area area : vo.getAreas()) {
                Area area1 = areaMapper.selectById(area);
                OrganizationalStructure structure = new OrganizationalStructure();
                structure.setParentId(vo.getId());
                structure.setChannelId(vo.getId());
                structure.setChannelName(vo.getName());
                structure.setName(area1.getName());
                structure.setType(2);
                structure.setExamine(0);
                structure.setAssociationId(area.getId());
                organizationalStructureMapper.insert(structure);
                List<Area> areas = areaMapper.selectList(new QueryWrapper<Area>().eq("parent_id", area1.getId()));
                for (Area area2 : areas) {
                    sum.add(area2);
                }
            }
            for (Area area : sum) {
                OrganizationalStructure structure = organizationalStructureMapper.selectOne(new QueryWrapper<OrganizationalStructure>()
                        .eq("association_id", area.getParentId()));
                OrganizationalStructure structuresheng =   new OrganizationalStructure();
                structuresheng.setParentId(structure.getId());
                Provinces byId1 =provincesMapper.selectOne(new QueryWrapper<Provinces>()
                        .eq("provinceid",area.getShengId()));
                structuresheng.setName(byId1.getProvince());
                structuresheng.setChannelId(vo.getId());
                structuresheng.setChannelName(vo.getName());
                structuresheng.setRegionId(structure.getId());
                structuresheng.setRegionName(structure.getName());
                structuresheng.setType(3);
                structuresheng.setExamine(0);
                structuresheng.setAssociationId(area.getShengId());
                organizationalStructureMapper.insert(structuresheng);
                List<Cities> cities = citiesMapper.selectList(new QueryWrapper<Cities>()
                        .eq("provinceid", byId1.getProvinceid()));
                for (Cities city : cities) {
                    sum1.add(city);
                }
            }
            for (Cities city : sum1) {
                OrganizationalStructure structuresheng = organizationalStructureMapper.selectOne(new QueryWrapper<OrganizationalStructure>()
                        .eq("association_id", city.getProvinceid()));
                OrganizationalStructure organizationalStructure =   new OrganizationalStructure();
                organizationalStructure.setParentId(structuresheng.getId());
                organizationalStructure.setName(city.getCity());
                organizationalStructure.setChannelId(vo.getId());
                organizationalStructure.setChannelName(vo.getName());
                organizationalStructure.setRegionId(structuresheng.getRegionId());
                organizationalStructure.setRegionName(structuresheng.getRegionName());
                organizationalStructure.setShengId(structuresheng.getId());
                organizationalStructure.setShengName(structuresheng.getName());
                organizationalStructure.setType(4);
                organizationalStructure.setAssociationId(Long.parseLong(city.getCityid()));
                organizationalStructure.setExamine(0);
                organizationalStructureMapper.insert(organizationalStructure);
                List<Areas> areas1 = areasMapper.selectList(new QueryWrapper<Areas>()
                        .eq("cityid", city.getCityid()));
                for (Areas areas : areas1) {
                    sum2.add(areas);
                }
            }
            for (Areas areas : sum2) {
                OrganizationalStructure organizationalStructure = organizationalStructureMapper.selectOne(new QueryWrapper<OrganizationalStructure>()
                        .eq("association_id", areas.getCityid()));
                OrganizationalStructure organizae =   new OrganizationalStructure();
                organizae.setParentId(organizationalStructure.getId());
                organizae.setName(areas.getArea());
                organizae.setChannelId(vo.getId());
                organizae.setChannelName(vo.getName());
                organizae.setRegionId(organizationalStructure.getRegionId());
                organizae.setRegionName(organizationalStructure.getRegionName());
                organizae.setShengId(organizationalStructure.getShengId());
                organizae.setShengName(organizationalStructure.getShengName());
                organizae.setShiId(organizationalStructure.getId());
                organizae.setShiName(organizationalStructure.getName());
                organizae.setType(5);
                organizae.setExamine(0);
                organizationalStructureMapper.insert(organizae);

            }

//            for (Area area : vo.getAreas()) {
//                Area area1 = areaMapper.selectById(area);
//                OrganizationalStructure structure = new OrganizationalStructure();
//                structure.setParentId(vo.getId());
//                structure.setChannelId(vo.getId());
//                structure.setChannelName(vo.getName());
//                structure.setName(area1.getName());
//                structure.setType(2);
//                structure.setExamine(0);
//                structure.setAssociationId(area.getId());
//                organizationalStructureMapper.insert(structure);
//                List<Area> areas = areaMapper.selectList(new QueryWrapper<Area>().eq("parent_id", area1.getId()));
//                for (Area area2 : areas) {
//                    OrganizationalStructure structuresheng =   new OrganizationalStructure();
//                    structuresheng.setParentId(structure.getId());
//                    Provinces byId1 =provincesMapper.selectOne(new QueryWrapper<Provinces>()
//                            .eq("provinceid",area2.getShengId()));
//                    structuresheng.setName(byId1.getProvince());
//                    structuresheng.setChannelId(vo.getId());
//                    structuresheng.setChannelName(vo.getName());
//                    structuresheng.setRegionId(structure.getId());
//                    structuresheng.setRegionName(structure.getName());
//                    structuresheng.setType(3);
//                    structuresheng.setExamine(0);
//                    organizationalStructureMapper.insert(structuresheng);
//                    List<Cities> cities = citiesMapper.selectList(new QueryWrapper<Cities>()
//                            .eq("provinceid", byId1.getProvinceid()));
//                    for (Cities city : cities) {
//                        OrganizationalStructure organizationalStructure =   new OrganizationalStructure();
//                        organizationalStructure.setParentId(structuresheng.getId());
//                        organizationalStructure.setName(city.getCity());
//                        organizationalStructure.setChannelId(vo.getId());
//                        organizationalStructure.setChannelName(vo.getName());
//                        organizationalStructure.setRegionId(structure.getId());
//                        organizationalStructure.setRegionName(structure.getName());
//                        organizationalStructure.setShengId(structuresheng.getId());
//                        organizationalStructure.setShengName(structuresheng.getName());
//                        organizationalStructure.setType(4);
//                        organizationalStructure.setExamine(0);
//                        organizationalStructureMapper.insert(organizationalStructure);
//                        List<Areas> areas1 = areasMapper.selectList(new QueryWrapper<Areas>()
//                                .eq("cityid", city.getCityid()));
//                        for (Areas areas2 : areas1) {
//                            OrganizationalStructure organizae =   new OrganizationalStructure();
//                            organizae.setParentId(organizationalStructure.getId());
//                            organizae.setName(areas2.getArea());
//                            organizae.setChannelId(vo.getId());
//                            organizae.setChannelName(vo.getName());
//                            organizae.setRegionId(structure.getId());
//                            organizae.setRegionName(structure.getName());
//                            organizae.setShengId(structuresheng.getId());
//                            organizae.setShengName(structuresheng.getName());
//                            organizae.setShiId(organizationalStructure.getId());
//                            organizae.setShiName(organizationalStructure.getName());
//                            organizae.setType(5);
//                            organizae.setExamine(0);
//                            organizationalStructureMapper.insert(organizae);
//                        }
//                    }
//                }
//            }

        }
    }

    @Override
    public List<OrganizationalStructure> zsnyz() {
        QueryWrapper<OrganizationalStructure> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("examine",1);
        queryWrapper.eq("type",6);
        List<OrganizationalStructure> energyStations = organizationalStructureMapper.selectList(queryWrapper);
        return energyStations;
    }

    @Override
    public BigDecimal mfxss(Long id) {

        QueryWrapper<OrganizationalStructure> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("examine",1);
        queryWrapper.eq("type",6);
        if (id!=null){
            queryWrapper.eq("id",id);
        }
        List<OrganizationalStructure> energyStations = organizationalStructureMapper.selectList(queryWrapper);
        BigDecimal installedCapacity=new BigDecimal(0);
        for (int i = 0; i < energyStations.size(); i++) {
            OrganizationalStructure organizationalStructure = energyStations.get(i);
            BigDecimal installedCapacity1 = organizationalStructure.getInstalledCapacity();
            installedCapacity1=installedCapacity1==null?new BigDecimal(0):installedCapacity1;
            installedCapacity=installedCapacity.add(installedCapacity1);

        }
        return installedCapacity;
    }

    //账号是否重复
    private boolean isExist(String username,Long id){
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",username);
        queryWrapper.in("type",10,11,20,21);
        if (id!=null){
            queryWrapper.notIn("id",id);
        }
        long count = userMapper.selectCount(queryWrapper);
        if (count>0){
            return true;
        }
        return false;
    }
    //参数是否合法
    private boolean arguments(UserVo user){
        if (user.getUsername()==null || user.getUsername()==null ){
            return false;
        }
//        if (user.getPassword().equals("") || user.getPassword().equals("")){
//            return false;
//        }
        if (user.getPhone().equals("") || user.getPhone().equals("")){
            return false;
        }
        return true;
    }
}
